package com.systop.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.systop.tea.common.R;
import com.systop.tea.entity.Address;
import com.systop.tea.service.AddressService;
import com.systop.tea.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/address")
public class AddressController {

    private final AddressService addressService;

    @GetMapping("/query")
    public R<List<Address>> query(Address address) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(address.getUserId() != null, Address::getUserId, address.getUserId());
        queryWrapper.eq(address.getIsDefault() != null, Address::getIsDefault, address.getIsDefault());
        List<Address> list = addressService.list(queryWrapper);

        return R.success(list);
    }

    @GetMapping("/{id}")
    public R<Address> queryById(@PathVariable Integer id) {
        Address address = addressService.getById(id);
        return R.success(address);
    }

    @PostMapping
    public R<String> add(@RequestBody Address address) {
        boolean row = addressService.save(address);
        if (row) {
            return R.success("地址添加成功");
        } else {
            return R.error("地址添加失败");
        }
    }

    @PutMapping("/default")
    @Transactional
    public R<String> modifyDefault(@RequestBody Address address) {
        boolean row = addressService.updateById(address);
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Address::getUserId, address.getUserId());
        updateWrapper.ne(Address::getAddressId, address.getAddressId());
        Address address1 = new Address();
        address1.setIsDefault(false);
        boolean row1 = addressService.update(address1, updateWrapper);
        if (row && row1) {
            return R.success("默认地址修改成功");
        } else {
            return R.error("默认地址修改失败");
        }
    }

    @PutMapping
    public R<String> modify(@RequestBody Address address) {
        boolean row = addressService.updateById(address);
        if (row) {
            return R.success("地址修改成功");
        } else {
            return R.error("地址修改失败");
        }
    }

    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Integer id) {
        boolean rows = addressService.removeById(id);
        if (rows) {
            return R.success("地址删除成功");
        } else {
            return R.error("地址删除失败");
        }
    }

}
